package cn.wolfcode.crm.service.impl;

import cn.wolfcode.crm.domain.Permission;
import cn.wolfcode.crm.domain.Role;
import cn.wolfcode.crm.mapper.RoleMapper;
import cn.wolfcode.crm.query.PageResult;
import cn.wolfcode.crm.query.QueryObject;
import cn.wolfcode.crm.service.IRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class RoleServiceImpl implements IRoleService{
    @Autowired
    RoleMapper mapper;

    public void deleteByPrimaryKey(Long id) {
        mapper.deleteRelation(id);
        mapper.deleteByPrimaryKey(id);
    }

    public void insert(Role record) {
        mapper.insert(record);

        //维护角色和权限的关系
        List<Permission> permissions = record.getPermissions();
        for (Permission permission : permissions) {
            mapper.saveRelation(record.getId(),permission.getId());
        }
    }

    public Role selectByPrimaryKey(Long id) {
        return mapper.selectByPrimaryKey(id);
    }

    public List<Role> selectAll() {
        return mapper.selectAll();
    }

    public void updateByPrimaryKey(Role record) {
        //维护与permission关系
        mapper.deleteRelation(record.getId());
        mapper.updateByPrimaryKey(record);

        List<Permission> permissions = record.getPermissions();
        for (Permission permission : permissions) {
            mapper.saveRelation(record.getId(),permission.getId());
        }
    }

    public PageResult query(QueryObject qo) {
        int total = mapper.queryForCount(qo);
        if (total == 0) {
            return new PageResult();
        }
        List<Role> rows = mapper.queryForList(qo);
        return new PageResult(rows, total);
    }
}
